package com.example.ui_demo_widget1;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

import java.util.List;

public class ListView2Activity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view2);
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.READ_CONTACTS)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_CONTACTS},1);
        }else {
            readContacts();
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode,  String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode==1){
            if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED);
            readContacts();
        }else {
            Toast.makeText(this,"未获得相应权限",Toast.LENGTH_SHORT).show();
            finish();
        }
    }
    private void readContacts(){
        ListView lvcontact = findViewById(R.id.lv_contact);
        Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        String[] from=new String[]{
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                ContactsContract.CommonDataKinds.Phone.NUMBER
        };
        int[] to = new int[]{R.id.lv_display_name,R.id.lv_phone_number};
        SimpleCursorAdapter adpater = new SimpleCursorAdapter(this, R.layout.listview_contact,
                cursor, from, to);
        lvcontact.setAdapter(adpater);
        lvcontact.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Cursor c= (Cursor) lvcontact.getItemAtPosition(i);
                int index = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                String msg=c.getString(index);
                Toast.makeText(ListView2Activity.this,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }
}